package com.my.code.concurrent;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 例子：我们首先随机产生了2000个整数存于数组中，然后创建了两个线程，一个线程寻找前1000个数的最大值，另个一线程寻找后1000个数的最大值。<br/>
 * 主线程比较这两个线程的返回结果来确定这2000个数的最大值，并验证是否正确。
 */
public class FutureDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int[] a = new int[2000];
        Random rd = new Random();
        for (int i = 0; i < 2000; i++) {
            a[i] = rd.nextInt(20000);
        }

        class FindMax implements Callable<Integer> {
            private int begin, end;
            private int a[];

            public FindMax(int a[], int begin, int end) {
                this.a = a;
                this.begin = begin;
                this.end = end;
            }

            @Override
            public Integer call() throws Exception {
                int maxInPart = a[begin];
                for (int i = begin; i <= end; i++) {
                    if (a[i] > maxInPart) {
                        maxInPart = a[i];
                    }
                }
                return maxInPart;
            }
        }

        FutureTask<Integer> findMaxInFirstPart = new FutureTask<>(new FindMax(a, 0, 999));
        FutureTask<Integer> findMaxInSecondPart = new FutureTask<>(new FindMax(a, 1000, 1999));

        new Thread(findMaxInFirstPart).start();
        new Thread(findMaxInSecondPart).start();

        int maxInFirst = findMaxInFirstPart.get();// 阻塞
        int maxInSecond = findMaxInSecondPart.get();// 阻塞
        System.out.println("Find Max by Thread is " + (maxInFirst > maxInSecond ? maxInFirst : maxInSecond));

        //验证结果是否正确
        int max = a[0];
        for (int i = 0; i < 2000; i++) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        System.out.println("loop find max is " + max);
    }
}